<?php

/**
 * 商标管理系统 v1.0.1
 *
 * 商业运营到ubtm.cn官网进行授权使用。
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.05.01
 * Update at：2025.07.03
*/

namespace App\Http\Controllers\Auth;

use App\Exceptions\JsonResponseException;
use App\Http\Controllers\Controller;
use App\Services\Auth\Guest as GuestService;
use App\Services\Auth\ValidatorGuest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

/**
 * 会员注册、退出
 */
class GuestController extends Controller
{
    /**
     * 用户注册
     *
     * @param Request $request
     * @param ValidatorGuest $validator
     * @param GuestService $guest
     * @return JsonResponse
     */
    public function register(Request $request, ValidatorGuest $validator, GuestService $guest): JsonResponse
    {
        try {
            // 数据验证
            $validatedData = $validator->register($request->all());

            $data = $guest->register($validatedData);
        }
        catch (ValidationException $e) {

            throw new JsonResponseException(implode(',', $e->errors()), 422);
        }

        return $this->sendResponse($data, 'User registered successfully', 201);
    }

    /**
     * 用户登录
     *
     * @param Request $request
     * @param ValidatorGuest $validator
     * @param GuestService $guest
     * @return JsonResponse
     */
    public function login(Request $request, ValidatorGuest $validator, GuestService $guest): JsonResponse
    {
        try {
            // 数据验证
            $validatedData = $validator->login($request->all());

            $data = $guest->login($validatedData);
        }
        catch (ValidationException $e) {

            throw new JsonResponseException(implode(',', $e->errors()), 422);
        }
        catch (Exception $e) {

            throw new JsonResponseException($e->getMessage(), 401);
        }

        return $this->sendResponse($data, 'User logined successfully');
    }

    /**
     * 登出
     *
     * @param Request $request
     * @param GuestService $guest
     * @return JsonResponse
     */
    public function logout(Request $request, GuestService $guest): JsonResponse
    {
        $guest->destroy();

        return $this->sendResponse([], 'Logged out successfully');
    }
}
